#include "head.h"

//获取传入的加密密码的盐值
static void getsalt(const char *pwd, char *salt){
    //找到最后一个'$'符的位置
    const char *last_dollar = strrchr(pwd, '$'); 
    if (last_dollar != NULL) {
        //如果找到了'$'，则计算前面内容的长度
        int length = last_dollar - pwd;
        //复制str头部到最后一个'$'的内容到salt中
        strncpy(salt, pwd, length);
        //在字符串后面加'\0'结尾
        salt[length] = '\0'; 
    }
}

//检查客户端登录的用户名和密码是否正确
void login_check(int net_fd, int *flag_break){
    while(1){
        //接收用户名和密码
        char uname[20] = {0};
        char password[20] = {0};
        int ret_recv = recv(net_fd, uname, sizeof(uname), MSG_WAITALL);
        if(ret_recv == 0){
            printf("客户端断开连接\n");
            *flag_break = 1;
            break;
        }
        recv(net_fd, password, sizeof(password), MSG_WAITALL);

        //判断用户名和密码是否正确
        int flag_login = 0;
        struct spwd *pwd = getspnam(uname);
        //如果用户名不存在
        if(pwd == NULL){
            printf("该用户不存在\n");
            flag_login = 1;
        }
        //如果用户名存在则判断密码是否正确
        else{
            char salt[1024] = {0};
            getsalt(pwd->sp_pwdp, salt);
            char *encrypted = crypt(password, salt);
            if(strcmp(encrypted, pwd->sp_pwdp)){
                flag_login = 2;
            }
        }
        send(net_fd, &flag_login, sizeof(int), MSG_NOSIGNAL);
        //读到正确的密码则退出循环
        if(flag_login == 0){
            break;
        }
    }
}
